import { Form, Input, InputNumber, Card } from 'antd'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/button'
import FormContainer from '@/components/container/FormContainer'
import { useMemo } from 'react'
import { formLabelCol, formWrapperCol } from '@/hooks/useForm'
import { findBugApi } from '@/apis/sourcemap'
import { usePageTransfer } from '@/hooks/usePageTransfer'
import { useState } from 'react'

export default function SourcemapForm() {
  const [errorInfo, setErrorInfo] = useState<{
    line: number
    column: number
    source: string
    sourceContent: string
    sourceLine: string
  } | null>(null)
  const { t } = useTranslation()
  const [form] = Form.useForm()
  const { getTransferredData } = usePageTransfer()
  const data = getTransferredData()
  const formProps = useMemo(
    () => ({
      form,
      layout: 'horizontal' as const,
      labelCol: formLabelCol,
      wrapperCol: formWrapperCol,
      autoComplete: 'off',
    }),
    [form]
  )

  // 定义表单验证规则
  const rules = {
    bugId: [{ required: true, message: '请输入bugId' }],
    line: [{ required: true, message: '请输入行数' }],
    column: [{ required: true, message: '请输入列数' }],
  }

  const handleFindBug = async () => {
    const values = form.getFieldsValue()
    const res = await findBugApi({
      bugId: values.bugId,
      line: values.line,
      column: values.column,
      sourcemapId: data.id,
    })
    setErrorInfo(res)
  }

  const renderSourceCode = () => {
    if (!errorInfo) return null

    return (
      <Card title="错误定位" className="mt-4">
        <div className="text-sm mb-2">
          <span className="font-bold">错误位置：</span>
          <span>
            第 {errorInfo.line} 行，第 {errorInfo.column} 列
          </span>
        </div>
        <div className="text-sm mb-2">
          <span className="font-bold">源文件：</span>
          <span>{errorInfo.source}</span>
        </div>
        <div className="bg-gray-100 p-4 rounded overflow-auto">
          <pre className="font-mono text-sm">{errorInfo.sourceContent}</pre>
        </div>
      </Card>
    )
  }

  return (
    <FormContainer title={'查看bug'}>
      <Form {...formProps}>
        <Form.Item label="文件指纹ID" name="bugId" rules={rules.bugId}>
          <Input placeholder="请输入文件指纹ID" />
        </Form.Item>

        <Form.Item label="行数" name="line" rules={rules.line}>
          <InputNumber min={1} precision={0} style={{ width: '100%' }} placeholder="请输入行数" />
        </Form.Item>

        <Form.Item label="列数" name="column" rules={rules.column}>
          <InputNumber min={1} precision={0} style={{ width: '100%' }} placeholder="请输入列数" />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 12, span: 8 }}>
          <Button type="primary" onClick={handleFindBug}>
            查看bug
          </Button>
        </Form.Item>
        {renderSourceCode()}
      </Form>
    </FormContainer>
  )
}
